import "../assets/css/app/index.css"
// import "../assets/css/chat/index.css"

import * as aui from "andy-aui/lib/index";

import "./app.css";

import "../app/base/app";

import "./polyfill"

import { customCompoents } from "andy-ui/src/vue-base/custom-components";
import BaseComponent from "../app/baseComponent";

import { AUI, Dom } from "andy-ui";

Dom.initBasicDom();

window.aui = aui;

window.AUI = AUI;

window.AUI.app = {};

window.AUI.app.BaseComponent = BaseComponent;

window.AUI.app.customCompoents = customCompoents; 

window.AUI.app.messageType = {
    CHAT: "chat"
};

window.customCompoents = customCompoents;

import "clusterize.js/clusterize.css"
import Clusterize from "clusterize.js/clusterize.js"
import Utils from "./dep"

// import initEditor from "./editor"

import initClient from "./client"

// import initDropZone from "./dropzone"

import "./message.compnent"

// import Push from "push.js";

import("push.js").then(function(exports) {
    window.Push = exports;
})

// import Filer from "./simple-filer";
import requestFile from "./file";
import FilerUtils from "./fileutils";

import "../ui/progress/progress"

import initFileSentComponent from "./filesent.component";
import initDownlodComponent from "./download.component";
import initFileMessageComponent from "./file-message.component";

function pickNotMyUser() {
    return window.talkTo.userID;
}

var fileCards = {};

function createFileCard(id) {
    return function (createElement, self) {
        return [
            createElement(
                'div',
                {
                    attrs: {
                        'id': id,
                    },
                    'class': 'aui-card aui-file-card aui-file-card--movie',
                    'style': 'width: 290px;'
                },
                [
                    createElement(
                        'div',
                        {
                            'class': 'aui-card__body aui-file-card__body',
                            domProps: {
                                innerHTML: `
<div class="aui-display-inline-block aui-file-card__typelogo">
    <svg class="icon" aria-hidden="true">
        <use xlink:href="#icon-movie"></use>
    </svg>
</div>
<div class="aui-display-inline-block aui-file-card__type">MOVIE</div>
`
                            },
                        }
                    ),
                    createElement(
                        'footer',
                        {
                            'class': 'aui-card__action aui-file-card__action',
                            domProps: {
                                innerHTML: `
<div class="aui-file-card__name">速度是多少.mp4</div>
<div class="aui-file-card__size">127M</div>
<div class="aui-file-card__status">已完成</div>
`
                            },
                        }
                    ),
                    createElement(
                        'aui-progress',
                        {
                            'class': 'aui-file-card__progress',
                            'props': {
                                value: 0
                            },
                            ref: "progress"
                        }
                    ),
                ]
            )

        ];
    }
}

function addTask(task) {
    var fileCardID = appMethods.appendMessage(
        currentUser.userID,
        "right",
        "https://static.zhilizhili.com/static/3828461873613813290.jpg",
        currentUser.userID,
        createFileCard(fileCardID),
        "");

    fileCards[task.fileID] = {
        elref: fileCardID
    };
}

window.addTask = addTask;

// var filer = new Filer({});
// function initFiler() {
//     window.filer = filer;



//     var file = {};

//     var fileNameTD = document.querySelector("#fileNameTD");
//     var inputFile = document.querySelector("#inputFile");
//     var startTransfer = document.querySelector("#startTransfer");
//     var selectedPeerID = "";



//     inputFile.addEventListener("change", function(e) {
//         file = e.target.files[0];
//     });

//     startTransfer.addEventListener("click", function(){
//         if (file && file.lastModifiedDate) {
//             selectedPeerID = pickNotMyUser();
//             filer.myID = myID;
//             filer.signalingChannel = window.ws;
//             filer.send(selectedPeerID, file)
//         } else {
//             console.log("select a file");
//         }
//     });
    

//     filer.on('task', function(task) {
//         addTask(task);
//     });
    
//     filer.on('closepeer', function (peerID, peer) {
//         console.log("一位群友刚刚失去了梦想");
//         console.log(peerID);
//         console.dir(peer);

//         delete filer.peers[ peerID ];
//     });

//     filer.on('progress', function({fileID, progress, fileName, fileURL}){
//         console.log(progress);
//         if (app.$refs[fileCards[fileID].elref]) {
//             app.$refs[fileCards[fileID].elref][0].$refs["progress"].value = Math.floor(progress * 100);
//         }

//         if (progress === 1 && fileURL){
//             if (app.$refs[fileCards[fileID].elref]) {
//                 app.$refs[fileCards[fileID].elref][0].$refs["progress"].value = 100;
//             }
//             fileNameTD.innerHTML = "<a href='" + fileURL + "' download>" + fileName + "</a>";
//         }
//     });

//     filer.on('status', function({fileID, status}){
//         // var statusTD = $("#status-" + fileID);
//         // statusTD.text(status);
//         if (status == 'done' || status == 'removed') {
//             // 检测chrome内部暂存空间
//             // checkQuota()
//         }
//     });

//     filer.on('error', function(err){
//         // not implemented yet
//     });
// }


var data = {};
var heights = [];
var lastnum = 0;

window.Utils = Utils;

var usercarditemtpl = function (imgsrc, title, content) {
    return  `
<div class="aui-media app-user-card-media">
    <div class="aui-layout aui-layout-grid">
        <div class="aui-layout__item">
            <img class="b-app-rounded-circle app-user-card-media__logo" 
                src="${imgsrc}">
        </div>
        <div class="aui-layout__item aui-media__body">
            <h5 title="${title}" class="app-user-card-media__title">${title}</h5>
            <div title="${content}" class="app-user-card-media__content">${content}</div>
        </div>
    </div>
</div>
`
}

function createUserCard(userId, title) {    
    var tpl = usercarditemtpl(
        "https://static.zhilizhili.com/static/3828461873613813290.jpg",
        title,
        ''        
    );
    lastnum++;
    data[userId] = tpl;
    return [tpl];
}

var app = {};
var appMethods = {
    appendMessage: function (userID, pos, src, title, content, append) {
        return app.appendMessage(userID, pos, src, title, content, append);
    }
};
var clusterize = {};

function closeWsConnection() {
    // 清除数据
    window.ws.close();
    window.globalUsers = {};
    window.filer = null;
}

initFileSentComponent();
initDownlodComponent();
initFileMessageComponent();

document.addEventListener("DOMContentLoaded", function (e) {
  
    clusterize = new Clusterize({
        rows: data,
        scrollId: 'scrollArea',
        contentId: 'contentArea'
    });

    var currentUser = {};

    initClient(app, currentUser, data, clusterize, createUserCard, appMethods, clientUtils);

    if (window.AUINavigator.getQueryVariable("multi") != window.AUINavigator.url.NOT_FOUND) {
        app.isMulti = true;
    }

    var ioclient = io(`ws://${globalServerAddress}:9750`);

    ioclient.on("connect", function () {
        console.log("我已经就绪");
        // 服务器重新连接
        startWsConnection();

        if (window.AUINavigator.getQueryVariable("multi") == window.AUINavigator.url.NOT_FOUND) {

        }
    });

    ioclient.on("duifanghuile", function () {
        // makeLinkLife(ioclient);
    });

    ioclient.on("disconnect", function () {
        console.log("我已经知道 准备滚蛋");
        // websocket server is close
        // notify all browsers 准备撤
        closeWsConnection();

        Push.create("服务器连接失败", {
            body: "服务器连接失败",
            icon: 'https://static.zhilizhili.com/static/3828461873613813290.jpg',
            timeout: 3000
        });
    });
});

let clientUtils = {
    send(client, msgType, data = {}) {
        client.send(JSON.stringify(Object.assign({
            msgType: msgType
        }, data)))
    }
};

// initEditor();

let appInstance = {
    el: "#application",
    data: {
        isMulti: false,
        header: "",        
        messages: [],
        disableSend: false,
        talkarea: ""
    },
    methods: {
        sendMessage() {
            this.disableSend = true;
            console.log(window.currentUser);           
            // var html = app.$refs.appeditor.editorshell.getHTML();
            var html = this.talkarea;
            if (html.length > 0) {
                clientUtils.send(window.ws, "chat", {
                    from: window.currentUser,
                    to: window.talkTo,
                    userID: window.currentUser.userID,
                    content: html
                });
            } 
        },
        appendMessage(from, type, src, title, content, append) {            
            var ref = from.userID + "__message" + Utils.randomStr(6);
            this.disableSend = false;
            this.messages.push({
                pos: type,
                src: src,
                title: title,
                content: content,
                append: append,
                ref: ref
            });
            this.talkarea = "";
            return ref;
        }        
    }
};

window.onAppMessage = function(type, msgObj) {
    var pos = (currentUser.userID === msgObj.from.userID ? "right" : "left");
    // appMethods.appendMessage(
    //     msgObj.origin,
    //     pos,
    //     'https://static.zhilizhili.com/static/3828461873613813290.jpg',
    //     msgObj.from.userID,
    //     function (createElement) {
    //         return [
    //             createElement(
    //                 'app-file-message',
    //                 {
    //                     props: {
    //                     }
    //                 }
    //             )
    //         ];
    //     },
    //     ''
    // );
    console.log(type);
    console.log(msgObj);
    if (type === window.AUI.app.messageType.CHAT) {
        // 出现滚动条时要滚动到最后
        appMethods.appendMessage(
            msgObj.origin,
            pos,
            'https://static.zhilizhili.com/static/3828461873613813290.jpg',
            msgObj.from.userID,
            function (createElement) {
                return [
                    createElement(
                        'div',
                        {
                            domProps: {
                                innerHTML: msgObj.origin.content
                            }
                        }
                    )
                ];
            },
            ''
        );
        setTimeout(function() {
            app.$refs.messages.scrollTop = 100000;
        }, 0);
    }
}

window.AUI.app.Link = {};

import("./link").then(function (exports) {
    window.AUI.app.Link.encodeFileBlob = exports.encodeFileBlob;
    window.AUI.app.Link.decodeFileBlob = exports.decodeFileBlob;
    window.AUI.app.Link.encodeFileBlobChunk = exports.encodeFileBlobChunk;
})

window.fileChunksInfo = {};

window.fileChunksInfo = {};

window.AUI.app.globalHandleFile = function (msgevent) {
    // console.log('------------------------------------');
    // console.log(msgevent.data);
    // console.log('------------------------------------');
    window.AUI.app.Link.decodeFileBlob(msgevent.data).then(function (decodeFile) {            
        var storename = decodeFile.meta.network.to + "_____" + decodeFile.meta.name;
        
        if (!fileChunksInfo[storename]) {
            // 第一次初始化
            fileChunksInfo[storename] = {
                meta: decodeFile.meta,
                size: decodeFile.meta.chunkInfo.size,
                chunks: [decodeFile.file],
                stack: 1
            };
        } else {
            fileChunksInfo[storename].chunks.push(decodeFile.file)
            fileChunksInfo[storename].stack += 1;
        }        

        console.log("receive chunk " + fileChunksInfo[storename].chunks.length);

        if (fileChunksInfo[storename].stack > fileChunksInfo[storename].size - 1) {
            console.log('------------------------------------');
            console.log("end");
            console.log('------------------------------------');
            app.$refs.download.setLink(decodeFile.meta.name, new Blob(fileChunksInfo[storename].chunks));
        }
    }).catch(function (e) {
        console.log('------------------------------------');
        console.log(e);
        console.log('------------------------------------');
    })
}

appInstance.methods.handleFileSent = function () {
    var file = document.getElementById("globalfilesent").files[0];
    if (file && file.lastModifiedDate) {
        try {
            var selectedPeerID = pickNotMyUser();            
            var fileBlobChunk = window.AUI.app.Link.encodeFileBlobChunk(file, {
                network: {
                    to: selectedPeerID
                }
            });

            var asyncTasks = [];

            for (var i = 0; i < fileBlobChunk.length; i++) {
                asyncTasks.push((function (index) {
                    return new Promise(function (resolve, reject) {
                        setTimeout(function() {
                            console.log("send chunk " + index);
                            window.ws.send(fileBlobChunk[index]);
                            resolve();
                        }, index * 1500);
                    })
                })(i));
            }

            Promise.all(asyncTasks);
        } catch (e) {
            console.log('------------------------------------');
            console.log(e);
            console.log('------------------------------------');
        }
    } else {
        console.log("select a file");
    }
};

app = new Vue(appInstance);

window.app = app;




